package cn.dakaqi.apps.group.admin.controller;

import cn.dakaqi.apps.group.admin.response.BaseAddressAppointDateVO;
import cn.dakaqi.apps.group.admin.response.SimpleBaseAddressVO;
import cn.dakaqi.entities.BaseAddress;
import cn.dakaqi.entities.PassportApply;
import cn.dakaqi.entities.PassportApplyOrder;
import cn.dakaqi.entities.PassportAppointmentDate;
import cn.dakaqi.services.BaseAddressService;
import cn.dakaqi.services.PassportApplyOrderService;
import cn.dakaqi.services.PassportApplyService;
import cn.dakaqi.services.PassportAppointmentDateService;
import cn.dakaqi.utils.Clock;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import cn.dakaqi.utils.qrcode.ImageType;
import cn.dakaqi.utils.qrcode.QRCode;
import cn.dakaqi.utils.sms.rongcloud.RongCloudSMS;
import com.mangofactory.swagger.annotations.ApiIgnore;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.*;

/**
 * Copyright: Copyright (c)2016
 * Company: 志愿者打卡器(www.dakaqi.cn)
 * 类名称: BaseAddressController <br>
 * 类描述: <br>
 *
 * @author: ChunYang.Zhang
 * @since: 2016/9/27 11:33
 * @version: 1.0.0
 */
@Controller
@RequestMapping(value = "/passportApply")
@Slf4j
@ApiIgnore
public class PassportApplyController
{
    @Autowired
    BaseAddressService baseAddressService;
    @Autowired
    PassportApplyService passportApplyService;
    @Autowired
    PassportApplyOrderService passportApplyOrderService;
    @Autowired
    PassportAppointmentDateService passportAppointmentDateService;

    @RequestMapping(value = "/apply", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request,RedirectAttributes redirectAttributes)
    {
        ModelAndView modelAndView = new ModelAndView("passportApply/index");
        modelAndView.addObject("passportApply",new PassportApply());
        return modelAndView;
    }
    @RequestMapping(value = "/next", method = RequestMethod.POST)
    public ModelAndView next(PassportApply passportApply,HttpServletRequest request,RedirectAttributes redirectAttributes)
    {
        //检查当前用户是否已预约过
        PassportApplyOrder temp = this.passportApplyOrderService.findAllCardNO(passportApply.getCardNO());
        if(null != temp)
        {
//            ModelAndView modelAndView = new ModelAndView("passportApply/error");
//            switch (temp.getStatus())
//            {
//                case PassportApplyOrder.STAUTS_WAITE:
//                case PassportApplyOrder.STAUTS_CHECK:
//                case PassportApplyOrder.STAUTS_SEND_WAITE:
//                    modelAndView.addObject("msg","您已预约过了,不可以重复预约");
//                    break;
//                case PassportApplyOrder.STAUTS_SEND_OK:
//                case PassportApplyOrder.STAUTS_ACTIVATED:
//                    modelAndView.addObject("msg","您的护照编号为："  + temp.getPassportNO());
//                    break;
//            }
//
//            return modelAndView;

            ModelAndView modelAndView = new ModelAndView("passportApply/finsh");

            PassportApplyOrder passportApplyOrder = passportApplyOrderService.findAllNum(temp.getNum());
            modelAndView.addObject("passportApplyOrder",passportApplyOrder);
            String qrcode = getQr(passportApplyOrder.getNum());
            modelAndView.addObject("qrcode",qrcode);
            return modelAndView;
        }
        ModelAndView modelAndView = new ModelAndView("passportApply/next");
        modelAndView.addObject("passportApply", passportApply);
        request.getSession().setAttribute("passportApply",passportApply);
        return modelAndView;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(PassportApply passportApply,HttpServletRequest request,RedirectAttributes redirectAttributes)
    {
        PassportApply temp = (PassportApply)request.getSession().getAttribute("passportApply");
        temp.setBassAddressId(passportApply.getBassAddressId());
        temp.setNote(passportApply.getNote());
        temp.setAppointmentTime(passportApply.getAppointmentTime());
        temp.setAppointmenDate(passportApply.getAppointmenDate());
        temp.setCreateTime(Clock.DEFAULT.getCurrentDate());
        passportApplyService.save(temp);
        PassportApplyOrder passportApplyOrder = passportApplyOrderService.findByCardNO(temp.getBassAddressId(),PassportApplyOrder.STAUTS_WAITE,temp.getCardNO());
        return "redirect:/passportApply/finsh/"+passportApplyOrder.getNum();
    }
    @RequestMapping(value = "/finsh/{num}", method = RequestMethod.GET)
    public ModelAndView finsh(@PathVariable("num") String num,HttpServletRequest request,RedirectAttributes redirectAttributes)
    {
        ModelAndView modelAndView = new ModelAndView("passportApply/finsh");

        PassportApplyOrder passportApplyOrder = passportApplyOrderService.findAllNum(num);
        modelAndView.addObject("passportApplyOrder",passportApplyOrder);
        String qrcode = getQr(passportApplyOrder.getNum());
        modelAndView.addObject("qrcode",qrcode);
        return modelAndView;
    }

    private static String getQr(String activityCode)
    {
        String qr = "";
        if(StringUtils.isNotBlank(activityCode))
        {
            ByteArrayOutputStream out = QRCode.from(activityCode).to(ImageType.PNG).stream();
            byte[] data = out.toByteArray();
            qr = new String(Base64.encodeBase64(data));
            log.info(qr);
        }
        return qr;
    }

    @RequestMapping(value = "/findAddressAppointTime/{baseAddressId}",method = RequestMethod.GET,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> findAddressAppointTime(@PathVariable("baseAddressId") Long baseAddressId,HttpServletRequest request)
    {
        JsonResult result = new JsonResult();
        try
        {
            try
            {

                List<BaseAddressAppointDateVO> vos = new ArrayList<BaseAddressAppointDateVO>();

                result.setCode(JsonResult.CODE_SUCCESS);

                String today = DateUtil.convertDefaultDateString(new Date());
                List<PassportAppointmentDate> temp = this.passportAppointmentDateService.findAfterByBaseaddressId(baseAddressId,today,null);
                if(null != temp && temp.size()>0)
                {
                    Map<String,List<String>> map = new HashMap<String,List<String>>();
                    for(PassportAppointmentDate pad:temp)
                    {
                        if(map.isEmpty() && map.size() == 0)
                        {
                            List<String> times = new ArrayList<String>();
                            times.add(pad.getTimes().trim());
                            map.put(pad.getDay().trim(),times);
                        }
                        else
                        {
                            List<String> times = map.get(pad.getDay());
                            if(null == times)
                            {
                                times = new ArrayList<String>();
                                times.add(pad.getTimes().trim());
                                map.put(pad.getDay().trim(),times);
                            }
                            else
                            {
                                times.add(pad.getTimes().trim());
                            }
                        }
                    }
                    for(Map.Entry entry:map.entrySet())
                    {
                        vos.add(new BaseAddressAppointDateVO((String)entry.getKey(),(List<String>)entry.getValue()));
                    }
                    result.setData(vos);
                    return new ResponseEntity(result,HttpStatus.OK);
                }
                else
                {
                    result.setData(new HashMap<>());
                    return new ResponseEntity(result,HttpStatus.OK);
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }

    @RequestMapping(value = "/findAddress/{area}",method = RequestMethod.GET,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> findAddress(@PathVariable("area") String area,HttpServletRequest request)
    {
        JsonResult result = new JsonResult();
        try
        {
            try
            {
                result.setCode(JsonResult.CODE_SUCCESS);
                List<BaseAddress> temp = this.baseAddressService.findByAddressLike(area);
                if(null != temp && temp.size()>0)
                {
                    List<SimpleBaseAddressVO> baseAddressList = new ArrayList<SimpleBaseAddressVO>();
                    for(BaseAddress ba:temp)
                    {
                        baseAddressList.add(new SimpleBaseAddressVO(ba.getId(), ba.getName()));
                    }
                    result.setData(baseAddressList);
                    return new ResponseEntity(result,HttpStatus.OK);
                }
                else
                {
                    result.setData(new HashMap<>());
                    return new ResponseEntity(result,HttpStatus.OK);
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
            result.setCode(JsonResult.CODE_SUCCESS);
            result.setMessage("");
        }
        catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }

    @RequestMapping(value = "/sendCode/{mobile}",method = RequestMethod.GET,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> sendCodeByRegister(@PathVariable("mobile") String mobile,HttpServletRequest request)
    {
        JsonResult result = new JsonResult();
        try
        {
            if(StringUtils.isBlank(mobile))
            {
                result.setMessage("手机不能为空");
                result.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(result, HttpStatus.OK);
            }
            try
            {
                String sessionId = RongCloudSMS.sendCode(mobile);
                request.getSession().setAttribute(mobile,sessionId);
            } catch (Exception e)
            {
                e.printStackTrace();
            }
            result.setCode(JsonResult.CODE_SUCCESS);
            result.setMessage("验证码已发送,请注意查收");
        }
        catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }
    @RequestMapping(value = "/checkCode/{mobile}/{code}",method = RequestMethod.GET,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> sendCodeByRegister(@PathVariable("mobile") String mobile,@PathVariable("code") String code,HttpServletRequest request)
    {
        JsonResult result = new JsonResult();

        //绕过验证码注册
        if (code.equalsIgnoreCase("dakaqiCode"))
        {
            result.setCode(JsonResult.CODE_SUCCESS);
            result.setMessage("验证码正确");
            return new ResponseEntity(result,HttpStatus.OK);
        }
        //检查验证码是否正确
        String sessionId = (String)request.getSession().getAttribute(mobile);
        if (StringUtils.isBlank(sessionId))
        {
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage("验证码不正确");
            return new ResponseEntity(result,HttpStatus.OK);
        }
        else
        {
            try
            {
                boolean F = RongCloudSMS.verifyCode(sessionId, code);
                if(F == true)
                {
                    request.getSession().removeAttribute(mobile);
                    result.setCode(JsonResult.CODE_SUCCESS);
                    result.setMessage("验证码正确");
                }

            } catch (Exception e)
            {
                e.printStackTrace();
                result.setCode(JsonResult.CODE_FAIL);
                result.setMessage("验证码不正确");
                return new ResponseEntity(result,HttpStatus.OK);
            }
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }

}
